#include "img_servlet.h"
#include "source/log.h"
#include <iostream>
#include <fstream>

namespace sylar {
namespace http {

static sylar::Logger::ptr g_logger = SYLAR_LOG_ROOT();

ImageServlet::ImageServlet(const std::string& path)
    :Servlet("ImageServlet")
    ,m_path(path) {
}

int32_t ImageServlet::handle(sylar::http::HttpRequest::ptr request
                           , sylar::http::HttpResponse::ptr response
                           , sylar::http::HttpSession::ptr session) {
    auto path = m_path + "/" + request->getPath();
    SYLAR_LOG_INFO(g_logger) << "handle path=" << path;
    if(path.find("..") != std::string::npos) {
        response->setBody("invalid path");
        response->setStatus(sylar::http::HttpStatus::NOT_FOUND);
        return 0;
    } 
    std::ifstream freader(path, std::ios::in | std::ios::binary);
    if(!freader) {
        response->setBody("invalid file");
        response->setStatus(sylar::http::HttpStatus::NOT_FOUND);
        return 0;
    }

   int begin,end;
    begin = freader.tellg();
    freader.seekg(0, std::ios::end);
    end = freader.tellg();
    size_t len = end - begin;
    //cout << "len: " << len <<endl;

    std::string img_bytes(len, '\0');
    freader.seekg(0, std::ios::beg);
    freader.read(&img_bytes[0], len);

    response->setBody(img_bytes);
    SYLAR_LOG_DEBUG(g_logger) << "output img";
    // response->setHeader("content-type", "m_content_type");
    return 0;
}

}
}
